<template>
  <div>
    <el-card>
      <el-row type="flex" justify="end" class="btn_box">
        <el-button
          @click="allot_weather"
          class="el-icon-s-tools"
          type="warning"
          size="mini"
        >&nbsp;&nbsp;分配气象站</el-button>
        <el-button
          @click="add_weather"
          class="el-icon-plus"
          type="success"
          size="mini"
        >&nbsp;&nbsp;添加气象站</el-button>
      </el-row>
      <el-table :data="tableData" border stripe style="width: 100%">
        <!-- <el-table-column type="selection" width="55"></el-table-column> -->
        <el-table-column type="expand">
          <template slot-scope="info1">
            <el-tooltip class="item" effect="dark" content="查看该气象站下的驱动元素" placement="top">
              <el-button
                size="mini"
                @click="weather_serial(info1.row.serial)"
                type="warning"
                plain
              >驱动元素</el-button>
            </el-tooltip>

            <el-tooltip class="item" effect="dark" content="解除绑定关系" placement="top">
              <el-button size="mini" @click="unbound(info1.row.id)" type="info" plain>解除绑定</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="180"></el-table-column>
        <el-table-column prop="flag" label="状态">
          <template slot-scope="info">
            <el-tag :type="info.row.tag">{{info.row.flags}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lng" label="经度"></el-table-column>
        <el-table-column prop="lat" label="纬度"></el-table-column>
        <el-table-column prop="battery" label="电量(%)"></el-table-column>
        <el-table-column prop="voltage" label="电压(V)"></el-table-column>
        <el-table-column width="240" prop label="操作">
          <template slot-scope="info1">
            <el-button @click="up_weather(info1.row)" type="primary" icon="el-icon-edit" circle></el-button>
            <el-button
              @click="detele_weather(info1.row.id)"
              type="danger"
              icon="el-icon-delete"
              circle
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 气象站弹框 -->
    <el-dialog @close="close_weather" title="编辑信息" :visible.sync="diaolg_weather_up" width>
      <el-form ref="form_weather_up" :model="form_weather_up" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="form_weather_up.name"></el-input>
        </el-form-item>

        <el-form-item label="经度">
          <el-input v-model="form_weather_up.lng"></el-input>
        </el-form-item>
        <el-form-item label="纬度">
          <el-input v-model="form_weather_up.lat"></el-input>
        </el-form-item>
        <!-- <el-form-item label="电量">
          <el-input v-model="form_weather_up.battery"></el-input>
        </el-form-item>
        <el-form-item label="电压">
          <el-input v-model="form_weather_up.voltage"></el-input>
        </el-form-item>-->
        <el-form-item v-if="add_weather_lock" label="序列号">
          <el-input v-model="form_weather_up.serial"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <!-- <el-input v-model="form_weather_up.flags"></el-input> -->
          <el-select v-model="form_weather_up.flag" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="100px" label="封面(气象站)">
          <el-upload
            class="avatar-uploader"
            action="https://www.raintec.cn/file/upload"
            :show-file-list="false"
            :on-change="up_change"
            :headers="headers"
          >
            <img
              v-if="form_weather_up.icon"
              :src="form_weather_up.icon"
              class="avatar"
              alt="封面未正常加载"
              title="点击切换封面"
            >
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-row type="flex" justify="end">
          <el-button @click="dialog_map_open(form_weather_up)">查看地图</el-button>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="diaolg_weather_up = false">取 消</el-button>
        <el-button type="primary" @click="up_date_a">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 地图 -->
    <el-dialog
      @close="init_map"
      class="map_class_"
      title="地图"
      :visible.sync="dialog_map"
      width="50%"
    >
      <p class="lng_lat"></p>

      <div
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <map1 v-if="r_lock" :map_obj="map_obj" @lng_lat="lng_lat"></map1>
      </div>
    </el-dialog>
    <!-- 驱动元素弹出层 -->
    <el-dialog class title="驱动元素列表" :visible.sync="dialog_ele" width="70%">
      <el-table :data="ele_list" border stripe style="width: 100%">
        <el-table-column prop="eId" label="对应元素id"></el-table-column>
        <el-table-column prop="elementName" label="元素名称"></el-table-column>
        <el-table-column prop="elementSort" label="排序顺序"></el-table-column>
        <el-table-column prop="elementUnit" label="元素单位"></el-table-column>
        <el-table-column prop="formula" label="计算公式"></el-table-column>

        <el-table-column prop="isMaster" label="是否是主要元素">
          <template slot-scope="info">
            <el-tag :type="info.row.isMaster?'success':'danger'">{{info.row.isMaster?'是':'否'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isUsed" label="是否使用">
          <template slot-scope="info">
            <el-tag :type="info.row.isUsed ?'success':'danger'">{{info.row.isUsed?'是':'否'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="serial" label="气象站地址"></el-table-column>
      </el-table>
    </el-dialog>

    <!-- 未被分配的气象站列表 -->
    <el-dialog class title="未被分配气象站" :visible.sync="dialog_n_weather" width="70%">
      <el-button @click="station_list_allot" type="warning" plain>确认分配</el-button>
      <el-table @select="select_weather" :data="n_weather" border stripe style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>

        <el-table-column prop="name" label="姓名" width="180"></el-table-column>
        <el-table-column prop="flag" label="状态">
          <template slot-scope="info">
            <el-tag :type="info.row.tag">{{info.row.flags}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lng" label="经度"></el-table-column>
        <el-table-column prop="lat" label="纬度"></el-table-column>
        <el-table-column prop="battery" label="电量(%)"></el-table-column>
        <el-table-column prop="voltage" label="电压(V)"></el-table-column>
        <!-- <el-table-column width="180" prop label="操作">
          <template slot-scope="info1">
            <el-button @click="up_weather(info1.row)" type="primary" icon="el-icon-edit" circle></el-button>
            <el-button
              @click="detele_weather(info1.row.id)"
              type="danger"
              icon="el-icon-delete"
              circle
            ></el-button>

            <el-tooltip class="item" effect="dark" content="查看该气象站下的驱动元素" placement="top">
              <el-button
                @click="weather_serial(info1.row.serial)"
                type="warning"
                icon="el-icon-eleme"
                circle
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>-->
      </el-table>
    </el-dialog>
    <!-- 选择站点 -->
    <el-dialog
      @close="close_select_s"
      class
      title="选择站点"
      :visible.sync="dialog_n_station"
      width="40%"
    >
      <el-select v-model="fomr_sid_wid.sId" placeholder="请选择">
        <el-option
          v-for="item in dialog_station_list"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog_n_station = false">取 消</el-button>
        <el-button type="primary" @click="up_sid_wid">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import map1 from "./map";
import Qs from "qs";
// import { map } from "./map";
var map = require("./map");
export default {
  components: {
    map1: map1
  },
  created() {
    this.one_data();
  },
  // beforeDestoy() {
  //   this.map_obj = {};
  //
  // },
  data() {
    return {
      // 初始化清除marker
      r_lock: false,
      map: map,
      tableData: [],
      // 点击气象站数据·
      form_weather_up: {},
      // 气象站弹框
      diaolg_weather_up: false,
      add_lock: false,
      // token
      headers: {
        token: window.sessionStorage.getItem("token")
      },
      // 共用一个表单的锁
      add_weather_lock: false,
      // 气象站状态
      options: [
        { value: "00", label: "离线" },
        { value: "01", label: "在线" },
        { value: "02", label: "报警" }
      ],
      loading: true,
      dialog_map: false,
      dialog_ele: false,
      ele_list: [],
      // 地图使用的经纬度
      map_obj: {},
      // 被勾选的气象站
      weather_id_arr: [],
      // 未被分配的气象站弹出框
      dialog_n_weather: false,
      // 未被分配的气象站
      n_weather: [],
      dialog_n_station: false,
      dialog_station_list: [],
      fomr_sid_wid: {}
    };
  },

  methods: {
    // 解除绑定关系
    unbound(id) {
      // let {data:res} = await this.$http(`/collectorSingle/release/${id}`)

      this.$confirm("此操作将解除气象站绑定, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          this.$message({
            type: "success",
            message: "解除成功!"
          });
          let { data: res } = await this.$http(
            `/collectorSingle/release/${id}`
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消解除"
          });
        });
      console.log(id);
    },
    // 选择站点 关闭事件 ， 重新获取未被分配的气象站
    async close_select_s() {
      this.allot_weather();
      this.fomr_sid_wid = {};
    },
    async up_sid_wid() {
      console.log(this.fomr_sid_wid);

      this.fomr_sid_wid.ids = this.weather_id_arr;
      let { data: res } = await this.$http.post(
        "/collectorSingle/connectToStation",
        this.fomr_sid_wid
      );
      if (res.status != 0) return this.$message.error(res.msg);
      this.$message.success(res.msg);
      this.dialog_n_station = false;
      console.log(res);
    },
    // 获取站点列表
    async station_list_allot() {
      let { data: res } = await this.$http("/station/list");
      this.dialog_n_station = true;
      this.dialog_station_list = res.datas;
    },
    // 弹出分配列表
    async allot_weather() {
      let { data: res } = await this.$http("/collectorSingle/listUnBind");

      this.dialog_n_weather = true;
      this.n_weather = res.datas;
      this.n_weather.forEach(item => {
        if (item.flag == "00") {
          item.flags = "离线";
          item.tag = "info";
        } else if (item.flag == "01") {
          item.flags = "在线";
          item.tag = "success";
        } else {
          item.flags = "报警";
          item.tag = "danger";
        }
      });
    },
    // 当某个站点的多选按钮被选中时，触发的事件(这个事件是为了找到被选中的站点的id)
    select_weather(weather_arr) {
      // 先准备好一个空数组
      this.weather_id_arr = [];
      // 遍历选中的站点，
      weather_arr.forEach(item => {
        // 拿到里边的id 放到data的空数组里
        this.weather_id_arr.push(item.id);
      });
    },
    // 初始化地图 清除marker标
    init_map() {
      this.r_lock = false;
      this.map_obj = null;
      // this.form_weather_up = {}
    },
    // 点击弹出驱动元素列表
    async weather_serial(serial) {
      //
      let { data: res } = await this.$http(
        `/driveElementSingle/listBySerial/${serial}`
      );
      //
      //

      this.dialog_ele = true;
      this.ele_list = res.datas;
    },
    // 地图传过来的经纬度
    lng_lat(e) {
      //
      if (!e.lng) {
        e.lng = 0;
        e.lat = 0;
      }
      var form_ = this.form_weather_up;
      form_.lng = e.lng;
      form_.lat = e.lat;

      // 点击时候做一个提示p标签
      document.querySelector(".lng_lat").innerHTML = `已选择 经度：${
        e.lng
      },纬度：${e.lat}`;
    },
    // 点击选择经纬度 地图初始化
    dialog_map_open(e) {
      //
      // e = {};

      var _this = this;
      this.r_lock = true;
      this.dialog_map = true;
      this.map_obj = {
        lng: e.lng,
        lat: e.lat
      };

      //

      setTimeout(() => {
        this.lng_lat(e);

        this.loading = false;
      }, 1000);
    },
    // 添加气象站
    async add_weather() {
      // 更改表单为 添加状态
      this.add_weather_lock = true;
      // 默认添加在当前 站点下
      // this.form_weather_up.sId = this.station_id;
      // 打开弹出层
      this.diaolg_weather_up = true;
      // 开启气象站状态
      this.map_lock = true;
    },
    // 删除气象站
    detele_weather(id) {
      this.$confirm("此操作将永久删除该气象站, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          let { data: res } = await this.$http.delete(
            `/collectorSingle/delete/${id}`
          );
          // this.one_data();
          // this.more_(this.station_id);
          this.one_data();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 验证经纬度方法
    lat_90_lng_180(obj) {
      if (obj.lat > 90 || obj.lat < -90 || obj.lng > 180 || obj.lng < -180) {
        this.$message.error("请正确填写经纬度");
        return false;
      } else {
        return true;
      }
    },
    // 上传图片
    up_change(a) {
      setTimeout(() => {
        this.imgurl = a.response.data.path;
        this.form_weather_up.icon = this.imgurl;
        this.form_weather_up = { ...this.form_weather_up };
      }, 1000);
    },
    // 关闭气象站时的清除表单
    close_weather() {
      // 每次编辑完都 清空表单 ，为添加操作准备
      this.form_weather_up = {};
      // 清除添加气象站状态
      this.add_weather_lock = false;
      // 不传经纬度
      // this.map_obj = null
      this.one_data();
    },
    // 点击气象站弹出框的确认按钮(发送ajax)
    async up_date_a() {
      // 编辑和添加通用一个弹出层
      var url = "/collectorSingle/update";
      // 点击添加气象站的时候 锁是为true的
      if (this.add_weather_lock) {
        // 更改路由地址 为添加气象站
        url = "/collectorSingle/add";
      }
      // 验证经纬度
      if (!this.lat_90_lng_180(this.form_weather_up)) return;
      // 发送请求
      // this.form_weather_up.sId = 1;
      var { data: res } = await this.$http.put(url, this.form_weather_up);

      // 弹出 请求结果
      if (res.status != 0) return this.$message.error("编辑失败");
      if (res.status == 0) this.$message.success("编辑成功");
      // 获取最新数据
      // this.more_(this.station_id);
      this.one_data();
      // 关闭弹出层
      this.diaolg_weather_up = false;
    },
    // 点击弹出修改气象站弹窗
    up_weather(obj) {
      this.form_weather_up = obj;
      this.diaolg_weather_up = true;
      this.map_obj = {
        lng: obj.lng,
        lat: obj.lat
      };
    },
    // 首屏数据
    async one_data() {
      let { data: res } = await this.$http("/collectorSingle/list");
      this.tableData = res.datas;
      this.tableData.forEach(item => {
        if (item.flag == "00") {
          item.flags = "离线";
          item.tag = "info";
        } else if (item.flag == "01") {
          item.flags = "在线";
          item.tag = "success";
        } else {
          item.flags = "报警";
          item.tag = "danger";
        }
      });
    }
  }
};
</script>

<style lang='less' scoped>
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

#container {
  width: 100%;
  height: 280px;
}
.btn_box {
  padding-right: 50px;
}

.el-table {
  margin-top: 20px;
}
</style>
